#include "ZFile.h"
namespace ZuiLib
{


ZFile::ZFile(void)
	:m_rwops(NULL)
{
}


ZFile::~ZFile(void)
{
	Close();
}

bool ZFile::OpenFile(const char *file,const char *mode)
{
	Close();
	m_rwops=SDL_RWFromFile(file,mode);
	if (!m_rwops)
	{
		LOG(LS_ERROR)<<"OpenFile error "<<file;
	}
	return m_rwops!=NULL;
}

bool ZFile::OpenMem(ZBufferPtr buffer)
{
	Close();
	m_rwops=SDL_RWFromMem(buffer->data(), buffer->size());
	if (m_rwops) {
		m_buffer = buffer;
	}
	return m_rwops!=NULL;
}

bool ZFile::OpenMem(const void *mem, int size)
{
	Close();
	m_rwops=SDL_RWFromConstMem(mem,size);
	return m_rwops!=NULL;
}

void ZFile::Close()
{
	if(m_rwops)
	{
		SDL_RWclose(m_rwops);
		m_rwops=NULL;
	}
	m_buffer = NULL;
}

Sint64 ZFile::Size()
{
	if(m_rwops)
		return SDL_RWsize(m_rwops);
	else
		return 0;
}

Sint64 ZFile::Seek(Sint64 offset,int whence)
{
	if(m_rwops)
		return SDL_RWseek(m_rwops,offset,whence);
	else
		return 0;
}

Sint64 ZFile::Tell()
{
	if(m_rwops)
		return SDL_RWtell(m_rwops);
	else
		return 0;
}

size_t ZFile::Read(void *ptr,size_t size, size_t maxnum)
{
	if (m_rwops)
	{
		return SDL_RWread(m_rwops,ptr,size,maxnum);
	}
	else
		return 0;
}

size_t ZFile::Write(const void *ptr,size_t size, size_t num)
{
	if (m_rwops)
	{
		return SDL_RWwrite(m_rwops,ptr,size,num);
	}
	else
		return 0;
}


size_t ZFile::WriteU8(uint8_t value)
{
	if(m_rwops)
		return SDL_RWwrite(m_rwops, &value, sizeof (value), 1);
	else
		return 0;
}


uint8_t ZFile::ReadU8()
{
    uint8_t value = 0;
	if(m_rwops)
		SDL_RWread(m_rwops, &value, sizeof (value), 1);
    return value;
}

size_t ZFile::WriteU16(uint16_t value)
{
    const uint16_t swapped = SDL_SwapLE16(value);
	if(m_rwops)
		return SDL_RWwrite(m_rwops, &swapped, sizeof (swapped), 1);
	else
		return 0;
}

uint16_t ZFile::ReadU16()
{
	uint16_t value = 0;
	if(m_rwops)
		SDL_RWread(m_rwops, &value, sizeof (value), 1);
    return SDL_SwapLE16(value);
}

size_t ZFile::WriteU32(uint32_t value)
{
    const uint32_t swapped = SDL_SwapLE32(value);
	if(m_rwops)
		return SDL_RWwrite(m_rwops, &swapped, sizeof (swapped), 1);
	else
		return 0;
}

uint32_t ZFile::ReadU32()
{
	uint32_t value = 0;
	if(m_rwops)
		SDL_RWread(m_rwops, &value, sizeof (value), 1);
    return SDL_SwapLE32(value);
}

size_t ZFile::WriteU64(uint64_t value)
{
    const uint64_t swapped = SDL_SwapLE64(value);
	if(m_rwops)
		return SDL_RWwrite(m_rwops, &swapped, sizeof (swapped), 1);
	else
		return 0;
}

uint64_t ZFile::ReadU64()
{
	uint64_t value = 0;
	if(m_rwops)
		SDL_RWread(m_rwops, &value, sizeof (value), 1);
    return SDL_SwapLE64(value);
}


size_t ZFile::WriteFloat(float value)
{
    const float swapped = SDL_SwapFloatLE(value);
	if(m_rwops)
		return SDL_RWwrite(m_rwops, &swapped, sizeof (swapped), 1);
	else
		return 0;
}

float ZFile::ReadFloat()
{
	float value = 0;
	if(m_rwops)
		SDL_RWread(m_rwops, &value, sizeof (value), 1);
    return SDL_SwapFloatLE(value);
}


}
